package com.javasm.mingming.login.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.javasm.mingming.adminuser.entity.AdminUser;
import com.javasm.mingming.common.R;
import com.javasm.mingming.login.service.LoginService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @author javasm
 * @version 0.1
 * @className LoginController
 * @descriptioin:
 * @date 2025/1/11 15:22
 * @since jdk11
 */
@RestController
@RequestMapping("/loginuser")
public class LoginController {

    @Resource
    LoginService loginService;

    @Resource
    HttpSession session;
    @Resource
    HttpServletResponse response;

    @PostMapping("/update/pasword")
    public String updatePassword(String uid,String password){
        loginService.updatePassword(uid,password);
        return "success";
    }
    @PostMapping("/json")
    public R jsonLogin(@RequestBody AdminUser adminUser){
        AdminUser adminUserNew = loginService.jsonLogin(adminUser);
        return R.ok(adminUserNew);
    }

    //发送图片验证码
    @GetMapping("/img/code")
    public void sendImgCode() throws IOException {
        //代码不用手敲,可以复制
        //图形验证码的配置
        Properties properties = new Properties();
        //配置图片的宽度
        properties.setProperty("kaptcha.image.width","150");
        //高度
        properties.setProperty("kaptcha.image.height","50");
        //随机数
        properties.setProperty("kaptcha.textproducer.char.string","0123456789");
        //验证码长度
        properties.setProperty("kaptcha.textproducer.char.length","4");
        //配置到配置类中 import com.google.code.kaptcha.util.Config;
        Config config = new Config(properties);
        //创建图片对象
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        kaptcha.setConfig(config);
        //随机验证码
        String code = kaptcha.createText();
        //图片对象
        BufferedImage image = kaptcha.createImage(code);
        //code存入session 方便校验
        session.setAttribute("json_code",code);

        //响应的头信息
        response.setContentType("image/jpeg");
        //获取 响应对象的 输出流
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        outputStream.close();
    }

    @GetMapping("/phone/code")
    public R sendPhoneCode(String phone){
        loginService.sendCode(phone);
        return R.ok();
    }

    @PostMapping("/phone")
    public R phoneLogin(@RequestBody AdminUser adminUser){
        AdminUser loginUser = loginService.phoneLogin(adminUser);
        return R.ok(loginUser);
    }
}
